package com.usj.dcalvo.ecommerce.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.usj.dcalvo.ecommerce.bean.ProductoBean;
import com.usj.dcalvo.ecommerce.dao.IProductoDAO;

@Repository
public class ProductoDaoImpl implements IProductoDAO {

	// SessionFactory lo inyecto con spring
	private SessionFactory sessionFactory;

	@Transactional
	@Override
	public List<ProductoBean> getAllProductos() {
		List<ProductoBean> list = null;
		try {
			list = this.sessionFactory.getCurrentSession()
					.createQuery("from ProductoBean").list();
		} catch (ObjectNotFoundException onfe) {
		}
		return list;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	@Transactional
	public ProductoBean getProductoPorId(Integer idProducto) {
		Criteria criteria = this.sessionFactory.getCurrentSession()
				.createCriteria(ProductoBean.class)
				.add(Restrictions.eq("id", idProducto))
				.setFetchMode("producto", FetchMode.JOIN);
		ProductoBean object = (ProductoBean) criteria.uniqueResult();
		return object;
	}

	@Override
	@Transactional
	public void addVenta(ProductoBean producto) {
		this.sessionFactory.getCurrentSession().merge(producto);
	}

}
